package com.etalk.crm.controller.workflow;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.pojo.WorkflowApproval;
import com.etalk.crm.pojo.WorkflowCreate;
import com.etalk.crm.pojo.WorkflowResult;
import com.etalk.crm.service.WorkflowService;
import com.etalk.crm.utils.OssGetObject;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;

/**
 * 工作流总控制
 * @author Jordan
 */
@RequestMapping("/workflow")
@Controller
public class WorkflowController {
    private static final Logger logger = LogManager.getLogger(WorkflowController.class);

    @Resource
    private WorkflowService workflowService;

    /**
     * 工作流列表
     * @param model 页面数据
     * @param record 查询条件
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return
     */
    @RequestMapping(value = "/list",method = {RequestMethod.POST,RequestMethod.GET})
    public String getWorkflowList(Model model,WorkflowResult record, Integer pageNum, Integer pageSize) {
        if (StringUtils.isEmpty(pageNum)){
            pageNum=1;
        }
        if (StringUtils.isEmpty(pageSize)){
            pageSize=10;
        }

        PageInfo<WorkflowResult> pageInfo=workflowService.searchWorkflowPage(record,pageNum,pageSize);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("record",record);
        model.addAttribute("listType",workflowService.searchWorkflowList());
        return "workflow/workflow_list";
    }

    @GetMapping("/init/class/{lessonId}")
    public String getClassInfo(Model model,@PathVariable("lessonId") int lessonId){
        model.addAllAttributes(workflowService.searchInitWorkflow(lessonId));
        model.addAttribute("lessonId",lessonId);
        return "workflow/workflow_add";
    }

    @GetMapping("/view/{workflowId}")
    public String getWorkflowView(Model model,@PathVariable("workflowId") long workflowId){
        model.addAllAttributes(workflowService.searchViewApprovalInfo(workflowId));

        return "workflow/workflow_approval_view";
    }

    @GetMapping("/init/edit/{workflowId}")
    public String initEditor(Model model,@PathVariable("workflowId")int workflowId){
        model.addAllAttributes(workflowService.searchInitEditWorkflow(workflowId));
        return "workflow/workflow_edit";
    }

    @GetMapping("/init/approval/{workflowId}/{approvalId}/{approvalState}")
    public String initApprovalInfo(Model model,@PathVariable("workflowId") long workflowId,@PathVariable("approvalId") int approvalId, @PathVariable("approvalState") int approvalState){
        model.addAllAttributes(workflowService.searchInitApprovalInfo(approvalId));
        model.addAttribute("approvalState",approvalState);
        model.addAttribute("approvalId",approvalId);
        return "workflow/workflow_approval";
    }

    /**
     * 创建保存工作流信息
     * @param record 工作流数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create",method = {RequestMethod.POST, RequestMethod.GET})
    public String addWorkflow(WorkflowCreate record){
        Map<String,Object> resultMap= new HashMap<> (2);
        int num=workflowService.addWorkflow(record);
        resultMap.put("status",num);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 保存修改后的工作流信息
     * @param record 修改后的数据
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit",method = {RequestMethod.POST, RequestMethod.GET})
    public String editWorkflow(WorkflowCreate record){
        Map<String,Object> resultMap= new HashMap<> (2);
        int num=workflowService.editWorkflow(record);
        resultMap.put("status",num);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 保存审批信息
     * @param record 审批信息
     * @return
     */
    @ResponseBody
    @PostMapping("/approval/submit")
    public String addApprovalResult(WorkflowApproval record) {
        Map<String,Object> resultMap= new HashMap<> (2);
        int num=workflowService.addApproval(record);
        resultMap.put("status",num);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 撤销工作流
     * @param workflowId 工作流id
     * @return
     */
    @ResponseBody
    @PostMapping("/revoke/{workflowId}")
    public String revokeWorkflow(@PathVariable("workflowId")int workflowId) {
        Map<String,Object> resultMap= new HashMap<> (2);
        int num=workflowService.revokeWorkflow(workflowId);
        resultMap.put("status",num);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 获取工作流种类
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/question/list/{processSettingId}",produces = "application/json; charset=utf-8")
    public String getTypeList(@PathVariable("processSettingId") int processSettingId){
        Map<String,Object> resultMap= new HashMap<> (2);
        List<Map<String,Object>> list = workflowService.searchWorkflowQuestionTypeList(processSettingId);
        resultMap.put("status",1);
        resultMap.put("data",list);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 上传附件
     * @param request
     * @return
     */
    @PostMapping(value = "/upload/attachment")
    @ResponseBody
    public String uploadAttachment(MultipartHttpServletRequest request, int lessonId,int processSettingId) {
        Map<String,Object> jsonMap = new HashMap<>();
        List<MultipartFile> files =request.getFiles("uploadFiles");
//        logger.info(files.size());
        List<String> listFilePath = new ArrayList<>();
        if (files.size() >0) {
            SimpleDateFormat sdfForFileName = new SimpleDateFormat("yyyyMMddHHmmss");
            String times=sdfForFileName.format(new Date());
            for (MultipartFile file:files) {
                String currentFileName = file.getOriginalFilename();
                String fileExt = currentFileName.substring(currentFileName.lastIndexOf(".") + 1).trim().toLowerCase();
                String[] allowedExt = new String[]{"jpg", "jpeg", "gif", "png", "mp3", "mp4", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "csv", "zip", "rar", "txt", "pdf"};

                String newName = "workflow_" + lessonId + "_" + processSettingId + "_" + times + "_"  + new Random().nextInt(1000) + "." + fileExt;
//                logger.info("new file name==>" + newName);
                try {
                    OssGetObject.uploadWorkflowAttachment(file, newName);
                    listFilePath.add("/crm/workflow/"+newName);
                } catch (Exception e) {
                    jsonMap.put("msg","上传失败");
                    continue;
                }
            }
        }
        jsonMap.put("listFilePath", listFilePath);
        return JSONObject.toJSONString(jsonMap);
    }

}
